package com.thoughtworks.bytecode2class.instruction;

import java.util.ArrayList;
import java.util.List;

public class TABLESWITCH extends Instruction {

    private int low;
    private int high;
    private List<Byte> jumpOffsets = new ArrayList<Byte>();
    private int padding;
    private int defaultOffset;

    TABLESWITCH(List<Byte> bytes, int offset) {
        super(OpCode.TABLESWITCH, bytes, offset);
        padding = 3 - offset % 4;
        parseDefaultOffset();
        parseLow();
        parseHigh();
        parseJumpOffset();
    }

    private byte i(int index) {
        return bytes.get(offset + padding + index);
    }

    private void parseJumpOffset() {
        int jumpOffsetCount = high - low + 1;
        for (int i = 0; i < jumpOffsetCount; i++) {
            int jumpOffset = n(i(13 + 4 * i), i(14 + 4 * i), i(15 + 4 * i), i(16 + 4 * i));
            jumpOffsets.add((byte)jumpOffset);
        }
    }

    private void parseHigh() {
         high = n(i(9), i(10), i(11), i(12));
    }

    private void parseLow() {
         low = n(i(5), i(6), i(7), i(8));
    }

    private void parseDefaultOffset() {
        defaultOffset = n(i(1), i(2), i(3), i(4));
    }

    @Override
    public int getParamCount() {
        return padding + 12 + (high - low + 1) * 4;
    }

    private int n(byte b1, byte b2, byte b3, byte b4) {
        return (b1 << 24) | (b2 << 16) | (b3 << 8) | b4;
    }
}
